import tcb from "@cloudbase/node-sdk";
import fs from "fs";
import config from "./config";

const dealDbMessage = (data: any, code = 0, message = "", others = {}) => {
  return {
    data,
    code,
    message,
    ...others,
  };
};
/**
 *
 * @param {*} file 上传的文件
 * @param {*} url 上传到服务器的路径
 * @returns
 */
const uploadFile = (file: any, url: string) => {
  const app = tcb.init(config.cloudConfig);
  return new Promise((resolve, reject) => {
    const ext = file.name.split(".").pop();

    app
      .uploadFile({
        cloudPath: `${url}/${Date.now() + "." + ext}`,
        fileContent: fs.createReadStream(file.path), //fs.createReadStream(file)
      })
      .then((res) => {
        app
          .getTempFileURL({
            fileList: [res.fileID],
          })
          .then((res) => {
            if (res.fileList.length > 0) {
              // @ts-ignore
              resolve(res.fileList[0].download_url);
            } else {
              resolve(false);
            }
          });
      })
      .catch((err) => {
        console.log("err", err);
        resolve(false);
      });
  });
};

const getCurrentTime = (fmt: string, date: Date): string => {
  let ret;
  const opt: any = {
    "y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
};

export { dealDbMessage, uploadFile, config, getCurrentTime };
